package com.szu.smart_illustrator.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.szu.smart_illustrator.common.R;
import com.szu.smart_illustrator.dto.param.user.*;
import com.szu.smart_illustrator.entity.User;
import com.szu.smart_illustrator.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    public R<String> resetPasswd(@RequestBody ResetPasswdParamDto dto){
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getEmail,dto.getEmail()));

       if(user == null){
           return R.error("用户不存在");
       }
        if(!(dto.getVerificationCode().equals(user.getVerificationCode())) ){
            return  R.error("邮箱验证码错误");
        }
        user.setPasswd(dto.getPasswd());
        return R.success("成功");
    }


    public R<String> getVerificationCode(@RequestBody GetVerificationCodeParamDto dto){

        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getEmail,dto.getEmail()));
        if(user == null){
            return R.error("账号不存在");
        }

        // Sender's email and password
        String senderEmail = "1564024431@qq.com";
        String senderPassword = "ygwxgpnsznpojgbf";

        // Recipient's email
        String recipientEmail = dto.getEmail();

        // Email subject and content
        String emailSubject = "Verification Code";

        Random random = new Random();

        String emailContent = String.format("%06d",random.nextInt(1000000));
        System.out.println("code:  "+emailContent);
        // Configuration properties for the SMTP server
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.qq.com");
        properties.put("mail.smtp.port", "587");

        // Create a session with the SMTP server
        Session session = Session.getInstance(properties);

        try {
            // Create a new email message
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(senderEmail));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
            message.setSubject(emailSubject);
            message.setText(emailContent);

            // Authenticate and send the email
            Transport transport = session.getTransport("smtp");
            transport.connect("smtp.qq.com", senderEmail, senderPassword);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

            System.out.println("Email sent successfully!");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
       userMapper.update(null,new UpdateWrapper<User>().lambda()
               .eq(User::getEmail,dto.getEmail())
               .set(User::getVerificationCode,emailContent)
       );
        return  R.success("发送成功");
    }


    public R<User> editUserInfo(@RequestBody EditUserInfoParamDto dto){
        User user = userMapper.selectById(dto.getUserId());
        BeanUtils.copyProperties(dto,user);
        userMapper.updateById(user);
        return R.success(user);

    }
    public R<User> getUserInfo( GetUserInfoParamDto dto){
        return  R.success(userMapper.selectById(dto.getUserId()));
    }

    public R<User> changePasswd( ChangePasswdParamDto dto){
        User user = userMapper.selectById(dto.getUserId());
        user.setPasswd(dto.getPasswd());
        userMapper.updateById(user);
        return R.success(user);
    }
    public R<User> login( LoginParamDto dto){
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda()
                .eq(User::getEmail, dto.getEmail())
        );
        if(user == null){
            return R.error("用户不存在,请输入正确邮箱");
        }
        if(!user.getPasswd().equals(dto.getPasswd())){
            return  R.error("密码错误，请重新输入");
        }
        return  R.success(user);
    }

    public R<User> addUser( AddUserParamDto dto){

        //判断邮箱是否已经被注册
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getEmail, dto.getEmail()));
        if(user !=null){
            return  R.error("邮箱已被注册");
        }

        User newUser = User.builder()
                .email(dto.getEmail())
                .name(dto.getNickName())
                .passwd(dto.getPasswd())
                .build();
        userMapper.insert(newUser);


        return R.success(newUser);
    }
}
